//
//  SKInstagramV2.m
//  ShareKit4QC
//
//  Created by 凯 赵 on 12-5-7.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "SHKInstagramV2.h"
#import "SHK.h"
#import "NSString+URLEncoding.h"
#import "SHKInstagramV2OAuthView.h"
#import "JSONKit.h"


static NSString *authorizeURL = @"https://api.instagram.com/oauth/authorize/";
//app key 信息
static NSString* InstagramV2ClientId =@"8ac179ff4b8f4c0f96737c6e7972d6e3";
static NSString* InstagramV2SecretKey =@"edd5a3c8d5564998bedcfc375249b8b3";
static NSString* InstagramV2RedirectURI =@"http://caitu.me";
//鉴权信息
static NSString *accessTokenKey = @"accessToken";
static NSString *uidKey=@"uid";

@interface InstagramV2()
- (void)storeAccessToken;
- (BOOL)restoreAccessToken;
- (void)deleteStoredAccessToken;
- (BOOL)authorize;
- (void)promptAuthorization;
@property (nonatomic, strong) NSString *accessToken;
@property (nonatomic, strong) NSString *uid;
@property (nonatomic, assign) NSTimeInterval expires_Time;
@end

@implementation InstagramV2
@synthesize accessToken = _accessToken;
@synthesize uid = _uid;
@synthesize expires_Time=_expires_Time;

#pragma mark – init
+ (id) sharedInstance {
    static dispatch_once_t onceToken = 0;
    __strong static id _sharedObject = nil;
    dispatch_once(&onceToken, ^{
        _sharedObject = [[InstagramV2 alloc]initWithHostName:@"api.instagram.com/v1" apiPath:nil customHeaderFields:nil];
    });
    return _sharedObject;
}
- (NSString *)sharerId
{
    return @"InstagramV2";
}
- (NSString *)sharerName
{
    return @"新浪微薄";
}
- (void) logout
{
    return [self deleteStoredAccessToken];
}
- (BOOL)islogin
{
    return [self isAuthorized];
}
- (BOOL)autologin
{
    return [self authorize];
}

#pragma mark – OAuth 过程
- (void)storeAccessToken
{	
	NSString *sharerId = [self sharerId];
	[SHK setAuthValue:self.accessToken forKey:accessTokenKey forSharer:sharerId];
    [SHK setAuthValue:self.uid forKey:uidKey forSharer:sharerId];
}

- (BOOL)restoreAccessToken
{
	if (self.accessToken != nil && self.uid !=nil)
		return YES;
    
    NSString *sharerId = [self sharerId];
	self.accessToken = [SHK getAuthValueForKey:accessTokenKey forSharer:sharerId];
    self.uid = [SHK getAuthValueForKey:uidKey forSharer:sharerId];
	
	return (self.accessToken != nil)&&(self.uid != nil);
}

- (void)deleteStoredAccessToken
{
	NSString *sharerId = [self sharerId];
	
    [SHK removeAuthValueForKey:accessTokenKey forSharer:sharerId];
    [SHK removeAuthValueForKey:uidKey forSharer:sharerId];
    
    self.accessToken =nil;
    self.uid=nil;
}

- (BOOL)isAuthorized
{		
	return [self restoreAccessToken];
}

- (void)promptAuthorization
{
    //https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code
    NSURL* callbackURL=[NSURL URLWithString:InstagramV2RedirectURI];
	NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?client_id=%@&response_type=code&redirect_uri=%@", authorizeURL, InstagramV2ClientId, [callbackURL.absoluteString URLEncodedString]]];
    
	SHKInstagramV2OAuthView *auth = [[SHKInstagramV2OAuthView alloc] initWithURL:url delegate:self];
	[[SHK currentHelper] showViewController:auth];	
	//[auth release];
}
- (void)tokenAuthorizeView:(SHKOAuthView *)authView didFinishWithSuccess:(BOOL)success queryParams:(NSMutableDictionary *)queryParams error:(NSError *)error
{
#warning 无网络状态下，授权页面会授权失败，此时，是否应该有所提示呢？
    if (!success && error) {
        NSLog(@"%@",[error localizedDescription]);
        [[SHK currentHelper] hideCurrentViewControllerAnimated:YES];
    }
    NSLog(@"tokenAuthorizeView");
}

- (NSURL *)authorizeCallbackURL
{
    NSLog(@"authorizeCallbackURL");
    return [NSURL URLWithString:InstagramV2RedirectURI];
}
- (BOOL)authorize
{
	if ([self isAuthorized])
		return YES;
	
	else 
		[self promptAuthorization];
	
	return NO;
}

- (void)tokenAuthorizeCancelledView:(SHKOAuthView *)authView
{
	[[SHK currentHelper] hideCurrentViewControllerAnimated:YES];	
    //[self authDidFinish:NO];
}

- (void)requestAccessTokenWithAuthorizeCode:(NSString *)code
{
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:InstagramV2ClientId, @"client_id",
                            InstagramV2SecretKey, @"client_secret",
                            @"authorization_code", @"grant_type",
                            InstagramV2RedirectURI, @"redirect_uri",
                            code, @"code", nil];
    
    //============
    /*
     {
     "access_token" = "753501.8ac179f.0ac4ea79c7fb42b8af778aecb734eb6e";
     user =     {
     bio = "";
     "full_name" = "\U51ef \U8d75";
     id = 753501;
     "profile_picture" = "http://images.instagram.com/profiles/anonymousUser.jpg";
     username = laok;
     website = "";
     };
     }
     */
    //============
    //注意：获取token的apipath 与微薄功能调用api 路径不一致
    //https://api.weibo.com/oauth2/access_token 
    MKNetworkOperation *op = [self operationWithURLString:@"https://api.instagram.com/oauth/access_token"
                                              params:params
                                               httpMethod:@"POST"];//
    
    [op onCompletion:^(MKNetworkOperation *completedOperation)
     {
         // the completionBlock will be called twice. 
         // if you are interested only in new values, move that code within the else block
         
         if([completedOperation isCachedResponse]) {
             DLog(@"Data from cache %@", [completedOperation responseJSON]);
         }
         else {
             DLog(@"Data from server %@", [completedOperation responseString]);
         }
         
         [[SHK currentHelper] hideCurrentViewControllerAnimated:YES];
         
         BOOL success = NO;
         
         NSMutableDictionary* dict = [[completedOperation responseString] objectFromJSONString];
         //NSDictionary *dict = (NSDictionary *)[completedOperation responseJSON] ;采用mknetwork的json解析，在这里会解析错误
         if ([dict isKindOfClass:[NSDictionary class]])
         {
             NSString *token = [dict objectForKey:@"access_token"];
             NSString *userID = [[dict objectForKey:@"user"]objectForKey:@"id"];
             
             success = token && userID;
             if (success) {
                 self.accessToken = token;
                 self.uid = userID;
                 [self storeAccessToken];
             }
         }
         
         
     }onError:^(MKNetworkOperation *completedOperation, NSError* error) {
         
         DLog(@"Data from server %@", [completedOperation responseString]);
     }];
    
    [self enqueueOperation:op forceReload:YES];//强制请求
    
}
- (void)authorizeWebView:(SHKInstagramV2OAuthView *)webView didReceiveAuthorizeCode:(NSString *)code
{
    // 授权过程被 取消
    if (![code isEqualToString:@"21330"])
    {
        [self requestAccessTokenWithAuthorizeCode:code];
    }
    else 
    {
        [[SHK currentHelper] hideCurrentViewControllerAnimated:YES];
    }
}

#pragma mark – API接口
-(MKNetworkOperation*)  requestAPI:(NSString*)apiPath
                        httpMethod:(NSString *)httpMethod
                            params:(NSDictionary *)params
                      onCompletion:(InstagramV2ResponseBlock) completionBlock
                           onError:(InstagramV2ErrorBlock) errorBlock{
    
    if (![self authorize]) {
        return nil;
    }
    NSMutableDictionary *mutableParams = [NSMutableDictionary dictionaryWithDictionary:params];
    [mutableParams setObject:self.accessToken forKey:@"access_token"];
    
    MKNetworkOperation *op = [self operationWithPath:apiPath
                                              params:mutableParams
                                          httpMethod:httpMethod
                                                 ssl:YES];//强制使用https
    
    NSLog(@"%@",[op curlCommandLineString]);
    [op onCompletion:^(MKNetworkOperation *completedOperation)
     {
         completionBlock([[completedOperation responseString]objectFromJSONString]);
         
     }onError:^(MKNetworkOperation *completedOperation, NSError* error) {
         //============临时处理======
         NSMutableDictionary* dict = [[completedOperation responseString] objectFromJSONString];
         if ([dict isKindOfClass:[NSDictionary class]])
         {
             int error_code = [[dict objectForKey:@"error_code"] intValue] ;
             NSString* error= [dict objectForKey:@"error"];
             switch (error_code) {
                 case 21327:
                     NSLog(@"%@,%d",error,error_code);
                     
                     [self deleteStoredAccessToken];
                     break;
                     
                 default:
                     break;
             }
             
         }
         //========================
         errorBlock([[completedOperation responseString]objectFromJSONString], error);
     }];
    
    [self enqueueOperation:op forceReload:YES];//强制请求
    
    return op;
}

-(MKNetworkOperation*)  update:(NSString*)text
                         image:(UIImage *)image
                  onCompletion:(InstagramV2ResponseBlock) completionBlock
                       onError:(InstagramV2ErrorBlock) errorBlock
{
    #warning Instagram not support update info.
    return nil;
}

/* instagram 目前不提供上传图片api，合作伙伴可以有
 正确回应：
 {
 "meta": {
 "code": 200
 },
 "data": {
 ...
 },
 "pagination": {
 "next_url": "...",
 "next_max_id": "13872296"
 }
 }
 错误回应：
 {
 "meta": {
 "error_type": "OAuthException",
 "code": 400,
 "error_message": "..."
 }
 }
 请求下一段数据
 {
 ...
 "pagination": {
 "next_url": "https://api.instagram.com/v1/tags/puppy/media/recent?access_token=fb2e77d.47a0479900504cb3ab4a1f626d174d2d&max_id=13872296",
 "next_max_id": "13872296"
 }
 }
*/

/*
- (void)testInstgram
{
    if (![[InstagramV2 sharedInstance] autologin]) {
        return ;
    }
    
    textFieldResponse.text=@"";
    // NSString* apiPath = labelAPI.text;
    
    //https://api.instagram.com/v1/media/popular
    //http://instagr.am/developer/endpoints/
    
    
    //NSString* apiPath=@"media/popular";
    //https://api.instagram.com/v1/tags/snow/media/recent?access_token=753501.f59def8.b883f650c50f4e0d8fe41e699c7e1803
    NSString* apiPath=@"tags/美/media/recent";//snow 为tag，tag相关内容
    // NSString* apiPath=@"tags/美";//snow 为tag,tag相关内容的个数
    NSString* apiEncode = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)apiPath, nil, nil, kCFStringEncodingUTF8);
    apiPath = apiEncode;
    
    //https://api.instagram.com/v1/tags/nofilter?access_token=753501.f59def8.b883f650c50f4e0d8fe41e699c7e1803
    
    if (![apiPath length]) {
        return;
    }
    NSLog(@"%@",apiPath);
    
    //支持参数："count", "max_id"
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                            @"10", @"count",
                            //@"13872296",@"max_id",//见上文注释next_max_id
                            nil];
    
    NSLog(@"start");
    
    MKNetworkOperation* op= [[InstagramV2 sharedInstance] requestAPI:apiPath
                                                          httpMethod:@"GET"
                                                              params:params
                                                        onCompletion:^(NSDictionary* responseData){
                                                            //dosomething
                                                            NSLog(@"success");
                                                            int code = [[[responseData objectForKey:@"meta"] objectForKey:@"code"]intValue];
                                                            if (code ==200) {
                                                                NSLog(@"%@",[[[responseData objectForKey:@"data"] class] description]);
                                                                NSArray * array = [responseData objectForKey:@"data"];
                                                                int count =[array count];
                                                                NSLog(@"count:%d",count);
                                                                for (int i=0; i<count; i++) {
                                                                    NSDictionary* temp= [array objectAtIndex:i];
                                                                    NSLog(@"low:%@",[[[temp objectForKey:@"images"]objectForKey:@"low_resolution"]objectForKey:@"url"]);
                                                                    NSLog(@"standard:%@",[[[temp objectForKey:@"images"]objectForKey:@"standard_resolution"]objectForKey:@"url"]);
                                                                    NSLog(@"thumbnail:%@",[[[temp objectForKey:@"images"]objectForKey:@"standard_resolution"]objectForKey:@"url"]);
                                                                }
                                                                NSLog(@"end");
                                                                
                                                            }
                                                            
                                                        }onError:^(NSDictionary* responseData, NSError *error){
                                                            //dosomething
                                                            NSLog(@"error");
                                                            //NSLog(@"%@",responseData);
                                                            NSString *errINfo = [NSString stringWithFormat:@"%@ %@",responseData,[error localizedDescription]];
                                                        }];
}
*/ 

@end
